package timing.ukulele.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class CustomHttpBasicServerAuthenticationEntryPoint extends HttpBasicServerAuthenticationEntryPoint {
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-type", "application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> result = new HashMap<>(4);
        result.put("status", HttpStatus.UNAUTHORIZED);
        result.put("message", "鉴权失败");
        String resultJson;
        try {
            resultJson = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
            resultJson = "{}";
        }
        DataBuffer body = response.bufferFactory().wrap(resultJson.getBytes());
        return response.writeWith(Mono.just(body));
    }
}
